import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/x3_component_core.dart';
import 'package:x3_form_core/components/base_form_radio.dart';
import 'package:x3_form_core/provider/base_request_form_provider.dart';
import 'package:x3_form_core/business_components/base_request_form_container.dart';

class BaseRequestFormRadio extends StatefulWidget {

  BaseRequestFormRadio({Key key, @required this.request, this.requestSaveData}) : super(key: key);

  final BaseHttpRequestModel request;

  final RequestSaveData requestSaveData;

  @override
  _BaseRequestFormRadioState createState() => _BaseRequestFormRadioState();

}

class _BaseRequestFormRadioState extends State<BaseRequestFormRadio> {

  BaseRequestFormProvider _baseRequestFormProvider;

  /// 请求数据
  @override
  Widget build(BuildContext context) {
    _baseRequestFormProvider = BaseRequestFormProvider.of(context);
    return BaseRequestFormContainer(
      showSuffixIcon: false,
      request: widget.request,
      child: BaseScreenRefreshComponent(
        needRefreshIndicator: false,
        request: BaseScreenRequestModel(widget.request.inputApi, method: BaseHttpMethodEnum.GET),
        builder: (BaseHttpResultModel result) => _buildContent(context, result),
      ),
    );
  }

  /// 获取数据
  Widget _buildContent(BuildContext context, BaseHttpResultModel result) {
    if (result.success == true) {
      var items = result.data;
      if (items is List) {
        List<BaseKeyValueModel> _list = items.map((e) => BaseKeyValueModel.fromJson(e)).toList();
        dynamic value = _baseRequestFormProvider.getDataSource(widget.request) ?? widget.request.defaultValue;
        this._setDefaultValue();
        return BaseFormRadio(radioList: _list, selectedKey: value, callBack: (item) {
            _baseRequestFormProvider.setDataSource(widget.request, item.key);
            if (widget.requestSaveData != null) widget.requestSaveData(widget.request, _baseRequestFormProvider.getMapDataSource(widget.request));
          },
        );
      }
      return SizedBox();
    }
    return SizedBox();
  }

  void _setDefaultValue() {
    List<String> keys = _baseRequestFormProvider.dataSource.keys.toList();
    String defaultValue = widget.request.defaultValue ?? '';
    if ( keys.contains( widget.request.fieldName ) == false && defaultValue.length > 0 ) {
      _baseRequestFormProvider.setDataSource(widget.request, defaultValue);
    }
  }

}
